package com.wondertek.poms.service.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.exception.MessageCodes;
import com.wondertek.poms.common.log.MethodLog;
import com.wondertek.poms.common.utils.excel.ImportExcel;
import com.wondertek.poms.common.utils.validate.ValidateFilter;
import com.wondertek.poms.common.vo.PageBean;
import com.wondertek.poms.common.vo.ResultBean;
import com.wondertek.poms.core.service.IProductService;
import com.wondertek.poms.core.service.ISellingPriceService;
import com.wondertek.poms.dao.po.PrdInfo;
import com.wondertek.poms.dao.po.Product;
import com.wondertek.poms.dao.po.SellingPrice;
import com.wondertek.poms.dao.po.SellingPriceTag;
import com.wondertek.poms.dao.pojo.SellingPriceExcelPojo;
import com.wondertek.poms.dao.pojo.SellingPriceTagExcelPojo;
import com.wondertek.poms.service.vo.SellingPriceVo;
import oracle.jdbc.proxy.annotation.Post;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping(value = "/selling-price")
public class SellingPriceController {

    @Autowired
    private ISellingPriceService sellingPriceService;
    @Autowired
    private IProductService productService;

    @GetMapping(value = "/list")
    @ResponseBody
    public ResultBean list(SellingPriceVo sellingPriceVo,
                           @RequestParam(defaultValue = "1") int page,
                           @RequestParam(defaultValue = "20") int rows,
                           @RequestParam(defaultValue = "CREATE_TIME") String sidx,
                           @RequestParam(defaultValue = "desc") String sord){
        SellingPrice sellingPrice=new SellingPrice();
        BeanUtils.copyProperties(sellingPriceVo,sellingPrice);
        Page<SellingPrice> list=sellingPriceService.findAll(sellingPrice,page,rows,sord,sidx);
        return PageBean.ok(list.getTotalPages(),list.getTotalElements(),list.getContent());
    }

    @PostMapping(value = "/add")
    @ResponseBody
    @MethodLog(module = "定价售价新增",insertDB=true,opterate = 1)
    public ResultBean add(@RequestBody SellingPriceVo sellingPriceVo){
        List<String> messageList = ValidateFilter.getFilterMessage(sellingPriceVo, Constants.VALIDATE_DEFAULT);
        if (!messageList.isEmpty()) {
            return ResultBean.error(messageList.toString());
        }

        /*if(sellingPriceVo.getSellingPriceNum()==null || sellingPriceVo.getProductId()==null){
            String msg="输入字段为空！";
            return ResultBean.error(msg);
        }*/

        if(isRepeat(sellingPriceVo)){
            return ResultBean.error(MessageCodes.get(MessageCodes.M980014));
        }


        SellingPrice sellingPrice=new SellingPrice();
        BeanUtils.copyProperties(sellingPriceVo,sellingPrice);
        Product product=productService.getByProductId(sellingPriceVo.getProductId().toString());
        sellingPrice.setPrice(product.getPrice());
        sellingPrice.setDescription(product.getDescription());
        sellingPrice.setName(product.getName());
        SellingPrice.putTimeAndUser(sellingPrice);
        sellingPriceService.save(sellingPrice);
        return ResultBean.ok();
    }

    @GetMapping(value = "/get-productIds")
    @ResponseBody
    public ResultBean getProductIds(String vo){
        List<Long> list=productService.getAllProductId(vo);
        return ResultBean.ok(list);
    }

    @PostMapping(value = "/import")
    @ResponseBody
    @MethodLog(module = "定价售价导入",insertDB=true,opterate = 6)
    public ResultBean importSellingPrice(MultipartFile file){
        StringBuffer msg = new StringBuffer("导入数据总数->");
        StringBuffer errMessage = new StringBuffer(".错误原因是->");
        AtomicInteger errNum = new AtomicInteger();// 全局错误数
        List<SellingPriceExcelPojo> list=new ArrayList<>();
        try{
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<SellingPriceExcelPojo> dataList=ei.getDataList(SellingPriceExcelPojo.class);
            if (CollectionUtil.isNotEmpty(dataList)) {
                msg.append(dataList.size() + ".错误数据数->");
                dataList.forEach(v -> importData(errMessage, errNum, v, list));
            } else {
                return ResultBean.error(MessageCodes.get(MessageCodes.M980205));
            }

            if (CollectionUtil.isNotEmpty(list)){
                for(SellingPriceExcelPojo pojo:list){
                    SellingPrice sellingPrice=new SellingPrice();
                    //BeanUtils.copyProperties(pojo,sellingPrice);
                    sellingPrice.setSellingPriceNum(Convert.toLong(pojo.getSellingPriceNum()));
                    sellingPrice.setProductId(Convert.toLong(pojo.getProductId()));
                    Product product=productService.getByProductId(pojo.getProductId());
                    sellingPrice.setPrice(product.getPrice());
                    sellingPrice.setDescription(product.getDescription());
                    sellingPrice.setName(product.getName());
                    SellingPrice.putTimeAndUser(sellingPrice);
                    sellingPriceService.save(sellingPrice);
                }

            }
            msg.append(errNum);
            msg.append(errMessage);
        }catch (Exception e){
            e.printStackTrace();
            return ResultBean.error(MessageCodes.get(MessageCodes.M980000));
        }
        if (errNum.get() > 0) {
            return ResultBean.error(msg.toString().replace("[", "").replace("]", "").replace("[]", "").replace("!", ""));
        }
        return ResultBean.ok();
    }

    public void importData(StringBuffer errMessage,AtomicInteger errNum,SellingPriceExcelPojo pojo,List<SellingPriceExcelPojo> list){
        if(pojo !=null){
            Boolean flag=true;
            List<String> messageList = ValidateFilter.getFilterMessage(pojo, Constants.VALIDATE_DEFAULT);
            flag = checkData(errMessage, errNum, pojo, flag, messageList);
            if (flag ) {
                list.add(pojo);
            }
        }
    }

    public Boolean checkData(StringBuffer errMessage,AtomicInteger errNum,SellingPriceExcelPojo pojo,Boolean flag,List<String> messageList){
        if (flag && !messageList.isEmpty()) {
            errNum.addAndGet(1);
            flag = false;
            errMessage.append("导入出错：" + messageList.toString() + ".  ");
        }
        if(flag && (pojo.getSellingPriceNum()==null || pojo.getProductId()==null)){
            errNum.addAndGet(1);
            flag = false;
            errMessage.append("导入出错：输入值必须为数字，不能为空.  ");
        }


        if(flag){
            Product product=productService.getByProductId(pojo.getProductId().toString());
            if(product==null){
                errNum.addAndGet(1);
                flag = false;
                errMessage.append("导入出错：计费点："+pojo.getProductId()+" 不存在.  ");
            }
        }

        if(flag){
            SellingPriceVo sellingPriceVo=new SellingPriceVo();
            sellingPriceVo.setSellingPriceNum(Convert.toLong(pojo.getSellingPriceNum()));
            if(isRepeat(sellingPriceVo)){
                errNum.addAndGet(1);
                flag = false;
                errMessage.append("导入出错：" + MessageCodes.get(MessageCodes.M980014) + ".  ");
            }
        }
        return flag;
    }

    public Boolean isRepeat(SellingPriceVo sellingPriceVo){
        SellingPrice temp=new SellingPrice();
        temp.setSellingPriceNum(Convert.toLong(sellingPriceVo.getSellingPriceNum()));
        Optional<SellingPrice> opt=sellingPriceService.findOne(Example.of(temp));
        if(opt.isPresent()){
            SellingPrice sellingPrice=opt.get();
            if(sellingPriceVo.getId()!=null && sellingPriceVo.getId()!=sellingPrice.getId()){
                return true;
            }
            if(sellingPriceVo.getId()==null){
                return true;
            }
        }
        return false;
    }
}
